import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:wx_faxian/const.dart';
import 'package:http/http.dart' as http;

class ChatPage extends StatefulWidget {
  const ChatPage({super.key});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage>
    with AutomaticKeepAliveClientMixin<ChatPage> {
  Widget _buildPopupMenuItem(String imgAsset, String title) {
    return Row(
      children: [
        Image.asset(imgAsset, width: 20, height: 20),
        const SizedBox(width: 10),
        Text(title, style: const TextStyle(color: Colors.white)),
      ],
    );
  }

  List<ChatModel> _datas = [];

  @override
  void initState() {
    super.initState();
    getDatas().then((value) {
      setState(() {
        _datas = value;
      });
    }).catchError((e) {
      print(e);
    }).whenComplete(() {
      // print(_datas);
    }).timeout(Duration(seconds: 1), onTimeout: () {
      print('请求超时');
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Chat'),
        centerTitle: true,
        backgroundColor: primaryColor,
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              color: const Color.fromRGBO(1, 1, 1, 0.5),
              offset: const Offset(
                0,
                40,
              ),
              child: const Icon(Icons.add),
              itemBuilder: (BuildContext context) {
                return [
                  PopupMenuItem(
                    child: _buildPopupMenuItem(
                      'images/faqiqunliao.png',
                      '发起群聊',
                    ),
                  ),
                  PopupMenuItem(
                    child: _buildPopupMenuItem(
                      'images/tianjiapengyou.png',
                      '添加朋友',
                    ),
                  ),
                  PopupMenuItem(
                    child: _buildPopupMenuItem(
                      'images/saoyisao.png',
                      '扫一扫',
                    ),
                  ),
                  PopupMenuItem(
                    child: _buildPopupMenuItem(
                      'images/shoufukuan.png',
                      '收付款',
                    ),
                  ),
                ];
              },
            ),
          )
        ],
      ),
      body: Container(
        child: _datas.isEmpty
            ? const Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: _datas.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(_datas[index].imageUrl),
                    ),
                    title: Text(_datas[index].name),
                    subtitle: Container(
                      alignment: Alignment.bottomCenter,
                      height: 25,
                      child: Text(
                        _datas[index].message,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                  );
                },
              ),
        // 异步请求数据，并渲染
        /*   child: FutureBuilder(
          future: getDatas(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  leading: CircleAvatar(
                    backgroundImage:
                        NetworkImage(snapshot.data[index].imageUrl),
                  ),
                  title: Text(snapshot.data[index].name),
                  subtitle: Container(
                    alignment: Alignment.bottomCenter,
                    height: 25,
                    child: Text(
                      snapshot.data[index].message,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                );
              },
            );
          },
        ), */
      ),
    );
  }

  Future<List<ChatModel>> getDatas() async {
    final url =
        Uri.parse('http://rap2api.taobao.org/app/mock/322207/api/chat/list');
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      return responseBody['chat_list'].map<ChatModel>((item) {
        return ChatModel.formMap(item);
      }).toList();
    } else {
      throw Exception('Failed to load album');
    }
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class ChatModel {
  final String imageUrl;
  final String name;
  final String message;

  ChatModel({
    required this.imageUrl,
    required this.name,
    required this.message,
  });

  factory ChatModel.formMap(Map<String, dynamic> map) {
    return ChatModel(
      imageUrl: map['imageUrl'],
      name: map['name'],
      message: map['message'],
    );
  }
}
